<template>
  <!-- 商品列表 -->
  <div>
    <el-card>
      <div slot="header">
        <span>商品列表</span>
      </div>
      <div class="content">
        <el-table :data="tableData" style="width: 100%">
          <!-- type="expand 和 Scoped slot 可以展开 -->
          <!-- el-table-column 展开的内容 -->
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form  inline class="demo-table-expand">
                <el-form-item label="商品ID">
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="商品名称">
                  <span>{{ props.row.name }}</span>
                </el-form-item>
                <el-form-item label="所属分类">
                  <span>{{ props.row.category }}</span>
                </el-form-item>
                <el-form-item label="商品价格">
                  <span>{{ props.row.price }}</span>
                </el-form-item>
                <el-form-item label="商品图片">
                  <span>{{ props.row.imgUrl }}</span>
                </el-form-item>
                <el-form-item label="商品时间" >
                  <span>{{ctime(props.row.ctime) }}</span>
                </el-form-item>
                <el-form-item label="商品评价">
                  <span>{{ props.row.rating }}</span>
                </el-form-item>
                 <el-form-item label="商品销量">
                  <span>{{ props.row.sellCount }}</span>
                </el-form-item>
                 <el-form-item label="商品描述">
                  <span>{{ props.row.goodsDesc }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>

          <el-table-column label="商品名称" prop="name"> </el-table-column>
          <el-table-column label="所属分类" prop="category"> </el-table-column>
          <el-table-column label="商品价格">
              <template slot-scope="scope"><span>￥{{scope.row.price.toFixed(2)}}</span></template> 
          </el-table-column>
          <el-table-column label="商品图片" width="100"> 
              <template slot-scope="scope"><img :src="scope.row.imgUrl" alt="" width="80" height="80"></template> 
          </el-table-column>
          <el-table-column label="商品描述" prop="goodsDesc"> </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope" class="edit-del">
                <el-button type="primary" size="small" @click="editFoodsHandel(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="delGoodsHandel(scope.row.id)">删除</el-button>
            </template>
                     
          </el-table-column>
        </el-table>
        <!-- 分页 -->
         <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
      <!-- 编辑 -->
      <el-drawer title="编辑商品" :visible.sync="drawer" size='35%'>
        <el-form :model="editGoodsForm" status-icon :rules="rules" ref="editGoodsForm" label-width="100px">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="editGoodsForm.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="category">
                <!-- 下拉框 -->
                <el-select v-model="editGoodsForm.category">
                    <el-option :lable='item' :value="item" v-for="item in cateList" :key="item">
                    </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商品价格" prop="price">
                <el-input-number v-model="editGoodsForm.price"></el-input-number>
              </el-form-item>
              <el-form-item label="商品图片" prop="imgUrl">
                <el-upload
                  class="avatar-uploader"
                  action="http://127.0.0.1:5000/goods/goods_img_upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="editGoodsForm.imgUrl" :src="editGoodsForm.imgUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="商品描述" prop="goodsDesc">
                 <el-input v-model="editGoodsForm.goodsDesc" type="textarea"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="submitForm">保存</el-button>
                <el-button @click="drawer=false">取消</el-button>
              </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
  </div>
</template>

<script>
import {goodsList,goodsCategories,goodsEdit,goodsDel} from '@/api/goods'
import dayjs from 'dayjs'
export default {
    data() {
      return { 
        tableData: [],//页面商品数据
        currentPage:1,//分页当前页
        pageSize:5,//每页显示条数
        total:0,//总条数
        drawer:false,//抽屉隐藏开关
        editGoodsForm:{},//编辑数据表单
        cateList:[],//商品分类数组
        rules: {
        //编辑表单名称
        name: [
          // message  提示店铺名称
          { required: true, message: "请输入店铺名称", trigger: "blur" },
          { min: 2, max: 100, message: "长度在 2 到 100 个字符", //错误提示
            trigger: "blur", //失去焦点触发
          },
        ],
        category:[
          // message  提示商品分类
          { required: true, message: "请选择商品分类", trigger: "blur" },],
        price:[
          // message  提示商品价格
          { required: true, message: "请选择商品价格", trigger: "blur" },],
        imgUrl:[
          // message  提示商品图片
          { required: true, message: "请选择商品图片", trigger: "blur" },],
        goodsDesc:[
          // message  提示商品描述
          { required: true, message: "请选择商品描述", trigger: "blur" },],

          }
      }
    },
    //方法
    methods:{
      async loadData(){
       let res = await goodsList( {currentPage:this.currentPage,pageSize:this.pageSize});
      //  console.log(res);//res是页面商品的数据和总条数
       let {total,data}=res;
       this.total=total;
       this.tableData=data;
      },
      //每页条数发生改变
      handleSizeChange(val){
        this.pageSize=val;
        this.loadData(); 
      },
      //当前页发生改变
      handleCurrentChange(val){
        this.currentPage=val;
        this.loadData(); 
      },
      //编辑
      async editFoodsHandel(row){
        this.drawer=true;//显示抽屉
        this.editGoodsForm={...row};//浅拷贝新地址
        let res =await goodsCategories()
        // console.log(res);//商品分类数组
        this.cateList=res;
      },
      //删除
      delGoodsHandel(id){
        // console.log(id);//商品id
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
           let{code,msg} = await goodsDel(id)
          if(code===0){
            this.$message({
              type:"success",
              message:msg,
            });
          //刷新页面
             this.loadData();
            }else this.$message.error(msg);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //上传成功
      handleAvatarSuccess(res){
      // console.log(res);//响应信息
      //显示上传的图片 回填显示
      this.editGoodsForm.imgUrl=res.imgUrl
     },
      //商品图片上传成功之前的处理函数  设置上传规则
      beforeAvatarUpload(file){
        const isJPG = file.type === 'image/jpeg'||file.type === 'image/png'||file.type === 'image/gif'||file.type === 'image/webp';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('头像图片仅支持 JPG|PNG|GIF|WEBP 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
        return isJPG && isLt2M;

      },
      //抽屉编辑保存
      async submitForm(){
         this.$refs.editGoodsForm.validate(async (valid) => {
        //点击提交按钮  找到表单  用validate()方法  表单都有值就是true
          let res = await goodsEdit(this.editGoodsForm)
          let {code,msg}=res;
        if (valid) {
          // console.log(res);//修改商品的数据
          if(code===0){
            this.$message({
              type:"success",
              message:msg,
            });
            //添加成功隐藏
            this.drawer=false;
            //刷新页面
            this.loadData();
          }else this.$message.error(msg);
          }else this.$message.error("请补全商品信息");
          }
          )
      },
      //展开的时间格式处理
      ctime(val){
         return   dayjs(val).format("YYYY-MM-DD HH:mm:ss")
      }

    },
    //生命周期
    created(){
      //刷新页面数据的函数
      this.loadData();
    }
  
};
</script>
 
<style lang="less" scoped>
 .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  //分页
  .el-pagination{
    margin: 20px 0;
  }

  .demo-table-expand{
    padding:0 60px !important;
  }
  //编辑表单
  .el-form{
    padding-right: 30px;
  }

  //图片
  /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }

  //编辑 删除 最小宽度
  /deep/.edit-del{
    width: 80px;
    background-color: rgb(124, 13, 13);
  }
</style>